#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SCons构建系统主文件
类似Android.mk的编译系统，支持多种编译目标
"""

import os
import sys
import sys
import logging
from pathlib import Path
from SCons.Script import *

# 配置logging
logging.basicConfig(level=logging.INFO, format='%(message)s')

# 获取build_tools目录路径（就是当前SConstruct脚本所在的目录）
# 首先尝试使用BUILD_PROJECT_ROOT环境变量
build_project_root = os.environ.get('BUILD_PROJECT_ROOT', os.getcwd())
build_tools_dir = os.path.join(build_project_root, 'build_tools')

# 创建构建环境
env = Environment()

# 设置构建项目根目录
# 优先使用系统环境变量，如果没有则使用当前目录的父目录
build_project_root = os.environ.get('BUILD_PROJECT_ROOT')
if build_project_root:
    env['BUILD_PROJECT_ROOT'] = build_project_root
else:
    # 当前目录是 build_tools，需要回到上级目录作为项目根目录
    env['BUILD_PROJECT_ROOT'] = os.path.dirname(build_tools_dir)

# 配置SCons签名数据库文件位置
# 确保out/intermediate目录存在
out_intermediate_dir = os.path.join(env['BUILD_PROJECT_ROOT'], 'out', 'intermediate')
if not os.path.exists(out_intermediate_dir):
    os.makedirs(out_intermediate_dir, exist_ok=True)

# 设置签名数据库文件路径
scons_sign_file = os.path.join(out_intermediate_dir, '.sconsign.dblite')
SConsignFile(scons_sign_file)

build_tools_root = os.environ.get('CUST_BUILT_TOOLS_ROOT')
if build_tools_root and os.path.exists(build_tools_root):
    env['BUILD_TOOLS_ROOT'] = build_tools_root
else:
    # 使用SConstruct文件所在的目录作为build_tools目录
    env['BUILD_TOOLS_ROOT'] = build_tools_dir
    if not os.path.exists(env['BUILD_TOOLS_ROOT']):
        logging.error(f"Build tools directory not found: {env['BUILD_TOOLS_ROOT']}")
        sys.exit(1)


# 加载默认构建脚本
default_script = os.path.join(build_tools_dir, 'default.py')
if os.path.exists(default_script):
    env.Tool('default', toolpath=[build_tools_dir])
else:
    logging.error(f"Default build script not found: {default_script}")
    sys.exit(1)

# 扫描并加载所有Module文件
env.ScanAndLoadModules('.')

# 使用atexit确保Phase5在构建完成后显示
import atexit

# 添加标志位避免重复显示
_build_result_shown = False

def show_build_result():
    global _build_result_shown
    if _build_result_shown:
        return
    _build_result_shown = True

    logging.info("")
    logging.info("╔═════════════════════════════════════════════════════════════════════════╗")
    logging.info("║                        Phase5 -- Build result                           ║")
    logging.info("╚═════════════════════════════════════════════════════════════════════════╝")

    # 检查构建是否成功
    build_success = getattr(env, '_build_success', True)

    # 检查SCons构建失败
    if hasattr(sys, 'exit_code') and sys.exit_code != 0:
        build_success = False

    # 检查SCons构建失败
    from SCons.Script import GetBuildFailures
    if GetBuildFailures():
        build_success = False

    if build_success:
        logging.info("✅ Build completed successfully!")
    else:
        logging.info("❌ Build failed!")

    build_time = env.get_build_time()
    logging.info(f"⏱️  Build time: {build_time}")
    logging.info("")

atexit.register(show_build_result)

logging.info("")
logging.info("╔═════════════════════════════════════════════════════════════════════════╗")
logging.info("║                        Phase4 -- Build execution                        ║")
logging.info("╚═════════════════════════════════════════════════════════════════════════╝")

# 处理目标编译
specific_target = GetOption('target')
try:
    if specific_target:
        logging.info(f"Building target: {specific_target}")
        build_result = env.BuildTarget(specific_target)
        if not build_result:
            # 目标不存在，不继续执行SCons构建
            env._build_success = False
            # 手动调用Phase5显示结果
            show_build_result()
            # 直接跳到结束，不执行SCons构建
            sys.exit(1)
    else:
        all_targets = env._target_registry.get_all_targets()
        logging.info(f"Building all targets ({len(all_targets)} targets):")
        for target in all_targets:
            logging.info(f"  - {target}")
        env.BuildAllTargets()
except Exception as e:
    env._build_success = False
    logging.error(f"Build error: {e}")